<template>
  <div class="booking-management-page">
    <h2>预订管理</h2>
    
    <!-- 筛选区域 -->
    <el-card class="filter-section">
      <div class="filter-form">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="用户名">
            <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item label="订单状态">
            <select v-model="filterForm.paymentStatus" class="custom-select">
              <option value="">全部状态</option>
              <option value="0">已预约</option>
              <option value="1">已支付</option>
              <option value="2">已退款</option>
              <option value="3">已失效</option>
              <option value="4">待退款</option>
              <option value="5">使用中</option>
              <option value="6">已完成</option>
            </select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list-section" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <el-button type="primary" @click="refreshOrders">刷新</el-button>
        </div>
      </template>

      <el-empty v-if="orders.length === 0" description="暂无订单数据" />

      <el-table v-else :data="filteredOrders" style="width: 100%">
        <el-table-column prop="orderId" label="订单ID" width="80">
          <template #default="{ row }">
            {{ row.orderId || row.order_id }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="预订用户" width="120">
          <template #default="{ row }">
            <el-tooltip effect="dark" :content="getUserTooltip(row)" placement="top">
              <span>{{ row.username || `用户#${row.userId || row.user_id}` }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="roomname" label="会议室" width="120">
          <template #default="{ row }">
            {{ row.roomname || `会议室#${row.roomId || row.room_id}` }}
          </template>
        </el-table-column>
        <el-table-column label="预订时间" width="300">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime || row.start_time) }} 至 {{ formatDateTime(row.endTime || row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalFee" label="金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalFee || row.total_fee }}
          </template>
        </el-table-column>
        <el-table-column prop="refundFee" label="退款金额" width="100">
          <template #default="{ row }">
            <span v-if="(row.refundFee || row.refund_fee) > 0">¥{{ row.refundFee || row.refund_fee }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusType(Number(row.paymentStatus))">
              {{ getPaymentStatusText(Number(row.paymentStatus)) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="showOrderDetails(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          background
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="订单详情"
      width="500px"
    >
      <div v-if="selectedOrder" class="order-details">
        <p><strong>订单ID：</strong>{{ selectedOrder.orderId || selectedOrder.order_id }}</p>
        <p><strong>预订用户：</strong>{{ selectedOrder.username || `用户#${selectedOrder.userId || selectedOrder.user_id}` }}</p>
        <p v-if="selectedOrder.realName"><strong>真实姓名：</strong>{{ selectedOrder.realName }}</p>
        <p v-if="selectedOrder.phone"><strong>联系电话：</strong>{{ selectedOrder.phone }}</p>
        <p><strong>会议室：</strong>{{ selectedOrder.roomname || `会议室#${selectedOrder.roomId || selectedOrder.room_id}` }}</p>
        <p><strong>开始时间：</strong>{{ formatDateTime(selectedOrder.startTime || selectedOrder.start_time) }}</p>
        <p><strong>结束时间：</strong>{{ formatDateTime(selectedOrder.endTime || selectedOrder.end_time) }}</p>
        <p><strong>订单金额：</strong>¥{{ selectedOrder.totalFee || selectedOrder.total_fee }}</p>
        <p><strong>订单状态：</strong>{{ getPaymentStatusText(selectedOrder.paymentStatus ) }}</p>
        <p v-if="selectedOrder.cancelTime || selectedOrder.cancel_time">
          <strong>取消时间：</strong>{{ formatDateTime(selectedOrder.cancelTime || selectedOrder.cancel_time) }}
        </p>
        <p v-if="selectedOrder.refundFee || selectedOrder.refund_fee">
          <strong>退款金额：</strong>¥{{ selectedOrder.refundFee || selectedOrder.refund_fee }}
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getOrdersByPage, pageByCondition, getOrdersByUserIds } from '@/apis/orders'
import { getRoomById} from '@/apis/room'
import { getUserById,  searchUserIdsByUsername } from '@/apis/user'

// 状态管理
const loading = ref(false)
const orders = ref([])
const selectedOrder = ref(null)
const detailsDialogVisible = ref(false)
const userStore = useUserStore()
const roomCache = ref({}) // 缓存会议室信息，避免重复请求
const userCache = ref({}) // 缓存用户信息，避免重复请求
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = ref({
  username: '',
  paymentStatus: ''
})

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  
  try {
    let response
    const hasUsernameFilter = filterForm.value.username.trim() !== '';
    const hasStatusFilter = filterForm.value.paymentStatus !== '';

    if (hasUsernameFilter) {
      const userSearchResponse = await searchUserIdsByUsername(filterForm.value.username.trim());
      if (userSearchResponse.code === 200 && userSearchResponse.data && userSearchResponse.data.length > 0) {
        const userIds = userSearchResponse.data.map(user => user.user_id);
        if (hasStatusFilter) {
          // 同时有用户名和订单状态筛选
          console.log('Fetching orders by user IDs and status');
          response = await getOrdersByUserIds(
            pagination.value.pageNum,
            pagination.value.pageSize,
            userIds,
            parseInt(filterForm.value.paymentStatus)
          );
        } else {
          // 只有用户名筛选
          console.log('Fetching orders by user IDs only');
          response = await getOrdersByUserIds(
            pagination.value.pageNum,
            pagination.value.pageSize,
            userIds
          );
        }
      } else {
        // 未找到匹配用户，直接返回空列表并提示
        orders.value = [];
        pagination.value.total = 0;
        loading.value = false;
        ElMessage.warning(userSearchResponse.msg || `未找到用户名为 "${filterForm.value.username}" 的用户`);
        return;
      }
    } else if (hasStatusFilter) {
      // 只有状态筛选
      console.log('Fetching orders by status only');
      response = await pageByCondition(
        pagination.value.pageNum,
        pagination.value.pageSize,
        { paymentStatus: parseInt(filterForm.value.paymentStatus) }
      );
    } else {
      // 没有筛选条件
      console.log('Fetching orders by page (no filters)');
      response = await getOrdersByPage(pagination.value.pageNum, pagination.value.pageSize);
    }
    
    console.log('Backend API response:', response);
    
    if (response.code === 200 && response.data) {
      // 检查返回数据结构，确保 total 字段存在
      if (response.data.records && typeof response.data.total !== 'undefined') {
        orders.value = response.data.records;
        pagination.value.total = response.data.total;
      } else if (Array.isArray(response.data)) {
        orders.value = response.data;
        pagination.value.total = response.data.length;
        console.warn('Backend returned array without total. Pagination might be inaccurate.');
      } else {
        orders.value = response.data.list || response.data.content || [];
        pagination.value.total = response.data.total || response.data.totalElements || 0;
      }
      
      // 获取会议室和用户信息，并添加到订单数据中
      const ordersWithRoomInfo = await fetchRoomNames(orders.value);
      const ordersWithAllInfo = await fetchUserNames(ordersWithRoomInfo);
      
      orders.value = ordersWithAllInfo;
      
      // 检查当前页是否为空，如果总数大于0，则尝试跳转到前一页
      if (orders.value.length === 0 && pagination.value.total > 0 && pagination.value.pageNum > 1) {
        console.log('Current page is empty, but total > 0. Going to previous page.');
        pagination.value.pageNum -= 1;
        fetchOrders();
      }
    } else {
      ElMessage.error(response.msg || '获取订单列表失败或返回数据格式不正确');
      orders.value = [];
      pagination.value.total = 0;
    }
  } catch (error) {
    console.error('获取订单列表出错:', error);
    ElMessage.error('获取数据时发生错误，请稍后重试');
    orders.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
}

// 获取会议室名称并添加到订单数据中
const fetchRoomNames = async (orderList) => {
  const ordersWithRoomNames = [...orderList]
  
  // 获取所有需要查询的会议室ID
  const roomIdsToFetch = orderList
    .filter(order => {
      const roomId = order.roomId || order.room_id
      // 过滤出需要获取名称的会议室ID（不在缓存中的）
      return roomId && !roomCache.value[roomId]
    })
    .map(order => order.roomId || order.room_id)
  
  // 批量获取会议室信息
  for (const roomId of roomIdsToFetch) {
    try {
      const response = await getRoomById(roomId)
      if (response.code === 200 && response.data) {
        // 缓存会议室信息
        roomCache.value[roomId] = response.data
      }
    } catch (error) {
      console.error(`获取会议室ID ${roomId} 信息失败:`, error)
    }
  }
  
  // 将会议室名称添加到订单数据中
  return ordersWithRoomNames.map(order => {
    const roomId = order.roomId || order.room_id
    const roomInfo = roomCache.value[roomId]
    
    return {
      ...order,
      roomname: roomInfo ? roomInfo.roomname : `会议室#${roomId}`
    }
  })
}

// 获取用户名称并添加到订单数据中
const fetchUserNames = async (orderList) => {
  const ordersWithUserNames = [...orderList]
  
  // 获取所有需要查询的用户ID
  const userIdsToFetch = orderList
    .filter(order => {
      const userId = order.userId || order.user_id
      // 过滤出需要获取名称的用户ID（不在缓存中的）
      return userId && !userCache.value[userId]
    })
    .map(order => order.userId || order.user_id)
  
  // 批量获取用户信息
  for (const userId of userIdsToFetch) {
    try {
      const response = await getUserById(userId)
      if (response.code === 200 && response.data) {
        // 缓存用户信息
        userCache.value[userId] = response.data
      }
    } catch (error) {
      console.error(`获取用户ID ${userId} 信息失败:`, error)
    }
  }
  
  // 将用户名称添加到订单数据中
  return ordersWithUserNames.map(order => {
    const userId = order.userId || order.user_id
    const userInfo = userCache.value[userId]
    
    return {
      ...order,
      username: userInfo ? userInfo.username : `用户#${userId}`,
      realName: userInfo ? userInfo.realName : '',
      phone: userInfo ? userInfo.phone : ''
    }
  })
}

// 获取用户工具提示信息
const getUserTooltip = (order) => {
  const userId = order.userId || order.user_id
  const userInfo = userCache.value[userId]
  
  if (!userInfo) return `用户ID: ${userId}`
  
  let tooltip = `用户名: ${userInfo.username}`
  if (userInfo.realName) tooltip += `\n真实姓名: ${userInfo.realName}`
  if (userInfo.phone) tooltip += `\n联系电话: ${userInfo.phone}`
  
  return tooltip
}

// 筛选订单 - 直接使用后端筛选
const filteredOrders = computed(() => {
  return orders.value
})

// 处理筛选
const handleFilter = () => {
  pagination.value.pageNum = 1 // 重置到第一页
  fetchOrders()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    username: '',
    paymentStatus: ''
  };
  pagination.value.pageNum = 1; // 重置到第一页
  fetchOrders();
}

// 刷新订单列表
const refreshOrders = () => {
  fetchOrders()
}

// 显示订单详情
const showOrderDetails = (order) => {
  selectedOrder.value = order
  detailsDialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  status = Number(status)
  if (isNaN(status)) return '未知'
  switch (status) {
    case 0: return '已预约'
    case 1: return '已支付'
    case 2: return '已退款'
    case 3: return '已失效'
    case 4: return '待退款'
    case 5: return '使用中'
    case 6: return '已完成'
    default: return '未知'
  }
}

// 获取支付状态类型
const getPaymentStatusType = (status) => {
  switch (status) {
    case 0: return 'success'  // 绿色
    case 1: return 'success'  // 绿色
    case 2: return 'warning'  // 黄色
    case 3: return 'danger'   // 红色
    case 4: return 'warning'  // 黄色
    case 5: return 'warning'  // 黄色
    case 6: return 'success'  // 绿色
    default: return 'info'
  }
}

// 处理页码变化
const handlePageChange = (newPage) => {
  pagination.value.pageNum = newPage
  fetchOrders()
}

// 处理每页显示数量变化
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize
  pagination.value.pageNum = 1 // 重置到第一页
  fetchOrders()
}

// 监听分页参数变化，自动重新获取数据
watch(
  () => [pagination.value.pageNum, pagination.value.pageSize],
  () => {
    // 只有当不是由于fetchOrders内部递归调用导致的页码变化时才触发（虽然这里没有直接的标志位来判断）
    console.log('Pagination parameters changed. Refetching orders.');
    fetchOrders();
  },
  { immediate: false } // 首次加载在 onMounted 中调用 fetchOrders
)

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.booking-management-page {
  padding: 2rem;
}

.filter-section {
  margin-bottom: 2rem;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-list-section {
  margin-bottom: 2rem;
}

.order-details {
  padding: 1rem;
}

.order-details p {
  margin: 0.5rem 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 60px;
}

.custom-select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  background-color: white;
  height: 42px;
  min-width: 180px;
}
</style> 